<?php

namespace App\Http\Controllers;

use App\Http\Models\Country;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CountryController extends Controller
{
	/**
	 * Display a listing of the resource.
	 *
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function index(Request $request)
	{
		//
		DB::enableQueryLog();
		if ($request->has('limit')) {
			$countries = Country::paginate($request->input('limit'));
		} else {
			$countries = Country::all();
		}

		return $this->table($countries, DB::getQueryLog());
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @param \Illuminate\Http\Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function store(Request $request)
	{
		//
		DB::enableQueryLog();
		$country = new Country;
		$country->name = $request->name;

		return $country->save() ?
			$this->success('', DB::getQueryLog()) : $this->failed('添加失败');
	}

	/**
	 * Display the specified resource.
	 *
	 * @param int $id
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function show($id)
	{
		//
		DB::enableQueryLog();
		return $this->success(Country::find($id), DB::getQueryLog());
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param int $id
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function update(Request $request, $id)
	{
		//
		DB::enableQueryLog();
		return Country::whereId($id)->update([
			'name' => $request->input('name')
		]) ? $this->success('', DB::getQueryLog()) : $this->failed('更新失败');
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param int $id
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function destroy($id)
	{
		//
		DB::enableQueryLog();
		return Country::where('id', $id)->delete() ? $this->success('', DB::getQueryLog()) : $this->failed('删除失败');
	}
}
